package com.fingard.dsp.bank.directbank.hbc01;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.directbank.hsbc01.EnumDirType;
import com.fingard.dsp.bank.directbank.hsbc01.HSBC01Base;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsHisBalDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpReceiver;

/**
 * @author XueJy on 2018/9/19.
 * @version 1.0
 */
public class HBC01Balance extends HBC01Base implements IBalance {
    DecimalFormat df = new DecimalFormat("0.00");

    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
        //查询账号
        String actNum = "";
        //查询币种
        String actCur = "";
        String actArea = "";
        //创建返回对象
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        //写返回ATS的统一头部信息
        retAts.writeStart();
        HSBC01Base hsbc01Base = new HSBC01Base();
        hsbc01Base.bankFront = this.bankFront;
        hsbc01Base.reqHeader = this.reqHeader;
        hsbc01Base.sbLog = this.sbLog;
        FtpReceiver ftpReceiver = hsbc01Base.downloadFile();
        if (ftpReceiver != null) {
            if (ConnState.FAIL.equals(ftpReceiver.connState) || (!ftpReceiver.isCompleted && !"file not exists".equals(ftpReceiver.connState))) {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(ftpReceiver.connState + "+" + ftpReceiver.connMsg);
                retAts.writeEnd();
                return retAts;
            }
        }
        String filePath942 = getTrimPath(hsbc01Base.getReceivePath(EnumDirType.MT942.getValue(), new Date()));
        while (p_req7506.readRecord()) {
            RetAtsBalDetail detail = new RetAtsBalDetail();
            actNum = p_req7506.readedDetail.actNum;
            actCur = convertCurToBank(p_req7506.readedDetail.actCur);
            actArea = p_req7506.readedDetail.actArea;
            detail.actCur = actCur;
            detail.actNum = actNum;
            detail.actArea = actArea;
            try {
                // 读取银行返回余额文件信息，组装报文发给ATS
                List<String> fileNames = getDirectoryAllFileName(filePath942);
                String latestFilename = "";
                //筛选出最新的MT942文件
                Date latestDate = null;
                Date receivedDate = null;
                String year = Format.Date8Format.format(new Date()).substring(0, 4);
                for (String fileName : fileNames) {
                    //MT942CN.EJ321.0719101358 52.088251418011.TXT
                    String[] msgInNames = fileName.split("\\.");
                    if (msgInNames.length >= 4) {
                        if (msgInNames[3].equals(actNum)) {
                            receivedDate = Format.DateTime14Format.parse(year + msgInNames[2].substring(0, 10));
                            if (latestDate == null) {
                                latestDate = receivedDate;
                                latestFilename = fileName;
                            } else if (receivedDate.getTime() > latestDate.getTime()) {
                                latestDate = receivedDate;
                                latestFilename = fileName;
                            }
                        }
                    } else {
                        WriteBankLogLn(fileName + "<---该MT942文件名有误");
                    }
                }
                if (!"".equals(latestFilename)) {
                    String contain = "";
                    synchronized (this) {
                        //读取文件内容
                        contain = FileHelper.readFileText(getTrimPath(filePath942) + File.separator + latestFilename, getCharset());
                    }
                    //对单个文件进行解析查找对应的账号明细信息 //"H", 明细头记录拆分符
                    String[] sArray1 = contain.split(":25:");
                    if (sArray1.length > 1 && sArray1[1].startsWith(actNum)) {
                        String spliter = "\n";
                        if (sArray1[1].contains("\r\n")) {
                            spliter = "\r\n";
                        }
                        String[] lines = contain.split(spliter);
                        for (String line : lines) {
                            if (line.startsWith("BAL")) {
                                //BAL PLGC8285818,18/CLGC26091469,45/CAVC26091469,45
                                //PLGC Posted Ledger Amount
                                //CLGC Current Ledger Amount
                                // Available balance
                                String[] bal = line.split("/");
                                String currCdFlag = bal[1].substring(3,4);
                                String availCdFlag = bal[2].substring(3,4);
                                BigDecimal currBal = new BigDecimal(convertCommaToPoint(bal[1].substring(4)));
                                BigDecimal availBal = new BigDecimal(convertCommaToPoint(bal[2].substring(4)));
                                if ("D".equals(currCdFlag)) {
                                    currBal = currBal.multiply(new BigDecimal("-1"));
                                }
                                if ("D".equals(availCdFlag)) {
                                    availBal = availBal.multiply(new BigDecimal("-1"));
                                }
                                detail.respCode = "0";
                                detail.frozenBal = df.format(currBal.subtract(availBal));
                                detail.availBal = df.format(availBal);
                                detail.currBal = df.format(currBal);
                                detail.respInfo = "";
                                retAts.writeRetDetail(detail, p_req7506.isBatch);
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                detail.respCode = "-1";
                detail.respInfo = "账号:" + actNum + "查询今日余额信息异常:" + ex.getMessage();
                retAts.writeRetDetail(detail, p_req7506.isBatch);
                WriteBankLogLn("账号:" + actNum + "查询今日余额信息异常:" + ex.getMessage());
            }
        }
        retAts.writeEnd();
        return retAts;
    }


    /**
     * 历史余额
     */
    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {

//        //创建返回对象
//        RetAts7505HisBalQry retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
//        //写返回ATS的统一头部信息
//        retAts.writeStart();
//        //待查询账号
//        String actNum = p_req7505.actNum;
//        String reqSeqId = p_req7505.reqHeader.transSeqID;
//        String actCur = convertCurToBank(p_req7505.actCur);
//        try {
//            //昨日余额查询
//            Calendar calendarFrom = Calendar.getInstance();
//            calendarFrom.setTime(p_req7505.getDateFrom());
//            Calendar calendarTo = Calendar.getInstance();
//            calendarTo.setTime(p_req7505.getDateTo());
//            if (calendarTo.getTime().getTime() > System.currentTimeMillis()) {
//                calendarTo.setTime(new Date());
//            }
//            Calendar amonthago = Calendar.getInstance();
//            amonthago.setTime(new Date());
//            //余额查询范围日期允许最大31天   MT940查询其实没限制
//            amonthago.add(Calendar.MONTH, -1);
//            if (calendarFrom.getTime().getTime() < amonthago.getTime().getTime()) {
//                calendarFrom = amonthago;
//            }
//
//            //存放历时余额详情Map Key为日期yyyy-MM-dd ,Value为当日余额
//            int numOfDate = calendarTo.get(Calendar.DAY_OF_YEAR) - calendarFrom.get(Calendar.DAY_OF_YEAR) + 1;
//            Map<String, String> prebalances = new HashMap<String, String>();
//            for (int x = 0; x < numOfDate; x++) {
//                prebalances.put(Format.Date10Format.format(calendarFrom.getTime()), "");
//                calendarFrom.add(Calendar.DAY_OF_YEAR, 1);
//            }
//            HSBC01Base hsbc01Base = new HSBC01Base();
//            FtpReceiver ftpReceiver = hsbc01Base.downloadFile();
//            //拷贝文件到本地路径
//            String mtPath = "";
////            String mtpath = hsbc01Base.getReceivePath("MT940", p_req1944.getBgnDateTime());
//            for (Map.Entry<String, String> history : prebalances.entrySet()) {
//                //指定日期路径yyyy-MM-dd
//                String fileDatePath = getTrimPath(mtPath) + File.separator + history.getKey().substring(0, 4) + history.getKey().substring(5, 7) + File.separator + history.getKey().substring(8, 10);
//                List<String> fileNames = getDirectoryAllFileName(fileDatePath);
//                //region 解析查询日期条件范围内的每日余额信息
//                for (String fileName : fileNames) {
//                    String alltext = "";
//                    synchronized (this) {
//                        //读取文件内容
//                        alltext = FileHelper.readFileText(getTrimPath(fileDatePath) + File.separator + fileName, getCharset());
//                    }
//                    //对单个文件进行解析查找对应的账号明细信息 //"H", 明细头记录拆分符
//                    String[] sArray1 = alltext.split(":25:");
//                    if (sArray1.length > 1 && sArray1[1].startsWith(actNum)) {
//                        //获取openingBalance
//                        DecimalFormat df = new DecimalFormat("0.00");
//                        String[] balanceArray = sArray1[1].split(":62F:");
//                        if (balanceArray.length > 1) {
//                            String cdFlag = balanceArray[1].substring(0, 1);
//                            //C150619CNY852244385,85
//                            String amt = balanceArray[1].substring(10, balanceArray[1].indexOf(",") + 3);
//                            amt=  convertCommaToPoint(amt);
//                            if ("D".equals(cdFlag)) {
//                                amt = "-" + amt;
//                            }
//                            history.setValue(amt);
//                            break;
//                        }
//                    }
//                }
//            }
//            for (Map.Entry<String, String> history : prebalances.entrySet()) {
//                RetAtsHisBalDetail retDetail = new RetAtsHisBalDetail();
//                retDetail.actBal = history.getValue();
//                //余额日期 yyyy-MM-dd
//                retDetail.balDate = history.getKey();
//                //历史余额、此余额是返回当前总余额还是当前可用余额
//                retAts.writeRetDetail(retDetail);
//            }
//        } catch (Exception e) {
//            if (!retAts.hasWrittenRespCode) {
//                retAts.writeRespCode("-1");
//            }
//            if (!retAts.hasWrittenRespInfo) {
//                retAts.writeRespInfo(e.getMessage());
//            }
//            retAts.writeEnd();
//            return retAts;
//        }
//        if (retAts.getWrittenRdCount() == 0) {
//            if (!retAts.hasWrittenRespCode) {
//                retAts.writeRespCode("0");
//            }
//            if (!retAts.hasWrittenRespInfo) {
//                retAts.writeRespInfo("返回结果为空，所查询时间段内不存在历史余额");
//            }
//            retAts.writeEnd();
//            return retAts;
//        }
//        retAts.writeEnd();
//        return retAts;
        return null;
    }
}
